import React, { useState, useEffect } from 'react'
import { Col, Form, Input, Button, Card, Select, message, Divider, Table  } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { formLayout } from '@/utils/utils'
import SearchBox from '@/components/SearchBox'
import { getMembersList, getVipLevel, getAvailCouponList, batchSendCoupon  } from '@/services/marketCenter/YHQ'

const SendCoupon = props => {
  const { form } = props
  const { getFieldDecorator } = form
  const [total, setTotalPage] = useState(null)
  const [dataList, setDataList] = useState([])
  const [vipLevel, setVipLevel] = useState([])
  const [availCouponList, setAvailCouponList] = useState([])
  const [idList, setIdList] = useState([])  // 批量选中的项
  const [visible, setVisible] = useState(false)
  const [param, setParam] = useState({
    pageNo: 1,
    pageSize: 10
  })
  useEffect(() => {
    _getVipLevel()
    _getMembersList(param)
    _getAvailCouponList()
  }, [])
  const _getMembersList = async (param) => {
    const res = await getMembersList(param)
    if (res.code == 0) {
      setDataList(res.data)
      setTotalPage(res.total)
    }
  }
  const _getVipLevel = async () => {
    const res = await getVipLevel()
    if (res.code == 0) {
      setVipLevel(res.data)
    }
  }
  const _getAvailCouponList = async () => {
    const res = await getAvailCouponList()
    if (res.code == 0) {
      setAvailCouponList(res.data)
    }
  }
  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)
      _getMembersList({
        ...param,
        ...values
      })
    })
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }
  const pagination = {
    total: parseInt(total),
    onChange (page) {
      _getMembersList({
        ...param,
        pageNo: page
      })
    }
  }
  const getFields = () => {
    return (<>
      <Col span={6}>
        <Form.Item label="昵称" labelCol={{ span:6 }} wrapperCol={{ span: 18 }}>
          {getFieldDecorator('nickname', {})
            (<Input />)}
        </Form.Item>
      </Col>
      <Col span={6}>
        <Form.Item label="手机号" labelCol={{ span:6 }} wrapperCol={{ span: 18 }}>
          {getFieldDecorator('phone', {})
            (<Input />)}
        </Form.Item>
      </Col>
      <Col span={6}>
        <Form.Item label="用户名" labelCol={{ span:6 }} wrapperCol={{ span: 18 }}>
          {getFieldDecorator('loginName', {})
            (<Input />)}
        </Form.Item>
      </Col>
      <Col span={6}>
        <Form.Item label="状态" labelCol={{ span:6 }} wrapperCol={{ span: 18 }}>
          {getFieldDecorator('statu', {initialValue: '',})(
            <Select>
              <Select.Option key={0} value={0}>已删除</Select.Option>
              <Select.Option key={1} value={1}>正常</Select.Option>
            </Select>,
          )}
        </Form.Item>
      </Col>
    </>)
  }
  const columns = [
    {
      title: '微信头像',
      dataIndex: 'userHeadImg',
      key: 'userHeadImg',
      render: (v, r, i) => {
        return (<img src={v} style={{width: '50px', height: '50px'}}/>)
      }
    },
    {
      title: '昵称/手机',
      dataIndex: 'nickname',
      key: 'nickname',
      render: (v, r, i) => {
        return (<>
          <span>{v}</span>
          <span>{r.phone}</span>
        </>)
      }
    },
    {
      title: '订单数/消费额',
      dataIndex: 'storeTradeTotal',
      key: 'storeTradeTotal',
      render: (v, r, i) => {
        return (<span>{r.tradeTotal} / {r.totalConsumption}</span>)
      }
    },
    {
      title: '账户余额',
      dataIndex: 'cashTotal',
      key: 'cashTotal',
    },
    {
      title: '最后消费时间',
      dataIndex: 'lastTradeTime',
      key: 'lastTradeTime'
    },
    {
      title: '注册时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (v, r, i) => {
        return (<span>{/\d{4}-\d{1,2}-\d{1,2}/g.exec(v)}</span>)
      }
    }
  ]
  const rowSelection = {
    onChange: (selectedRowKeys) => {
      setIdList(selectedRowKeys)
    }
  }
  const handleSendCounpon = async (idList) => {
    if (!idList.length) {
      message.warn('必须至少选中一条！')
      return
    }
    const res = await batchSendCoupon({
      couponId: form.getFieldValue('couponId'),
      userIdList: idList
    })
    if (res.code == 0) {
      message.success('发送成功！')
      _fetchAllCoupons(param)
    } else {
      message.error(res.msg)
    }
  }
  const handleToggle = () => {
    setVisible(!visible)
  }
  return (<PageHeaderWrapper>
    <Card>
      <Col span={8}>
        <Form.Item label={`选择优惠券`} labelCol={{ span:6 }} wrapperCol={{ span: 18 }}>
          {getFieldDecorator('couponId', {initialValue: '',})(
            <Select style={{width: '100%'}}>
              {availCouponList && availCouponList.map((r, index) => <Select.Option key={index} value={r.id}>{r.name}</Select.Option>)}
            </Select>,
          )}
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item labelCol={{ span:6 }} wrapperCol={{ span: 18 }}>
          <Button type="primary" onClick={handleSendCounpon} style={{margin: '0 10px'}}>发送</Button>
          <Button type="primary" onClick={handleToggle}>筛选</Button>
        </Form.Item>
      </Col>
      {
        visible && <>
          <Divider dashed />
          <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
        </>
      }
    </Card>
    <Card style={{marginTop: '10px'}}>
      <Table rowSelection={rowSelection} rowKey={record => record.id} pagination={pagination} size="small" columns={columns} dataSource={dataList}/>
    </Card>
  </PageHeaderWrapper>)
}

export default Form.create()(SendCoupon)
